package com.yanu.trace.t2s.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yanu.trace.t2s.entity.Pig;
import com.yanu.trace.t2s.entity.Pork;
import com.yanu.trace.t2s.service.PigService;
import com.yanu.trace.t2s.service.PorkService;
import com.yanu.trace.t2s.util.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/trace")
public class TraceController {
    @Autowired
    PorkService porkService;
    @Autowired
    PigService pigService;

    /**
     * 用于公示 无条件查询所有猪肉 并分页返回
     * @param info
     * @return
     */
    @PostMapping("/list")
    public Message list(@RequestBody String info) {
        Message msg = new Message();
        JSONObject jsonObject = JSONObject.parseObject(info);//转化为json对象
        IPage<Pork> iPage = porkService.selectPage(new Page<>(jsonObject.getLong("current"),
                jsonObject.getLong("size")));//分页查询全部猪肉
        if (iPage!=null) {
            msg.setSuccess(iPage);
        } else
            msg.setFail(409);
        return msg;
    }

    /**
     * 通过get方式 传入猪肉id 根据猪肉id查询这块猪肉的所有流通信息 最后形成溯源信息
     * 可以从中间节点往上查询
     * @param porkid
     * @return
     */
    @GetMapping("/{porkid}")
    public Message trace(@PathVariable Integer porkid)  //传入要溯源的猪肉id
    {
        Message msg = new Message();
        Map<String, Object> map = new HashMap<>();//分别存储porks和pig
        List<Pork> porks = new ArrayList<>();//溯源的porks数组
        Pork pork = porkService.selectByidPaE(porkid);
        porks.add(pork);
        int parentid = pork.getParent();
        int count = 0;//防止陷入无限循环
        while (true) {
            if (pork.getEnterprise().getType() == 1 ||pork.getLevel()==1)//如果传入的猪肉就是屠宰企业的
            {
                Pig pig = pigService.selectByidpae(pork.getParent());
                map.put("porks", porks);
                map.put("pig", pig);
                break;
            }
            count++;
            Pork pork1 = porkService.selectByidPaE(parentid);//获取这块肉的父肉块
            if (pork1 == null) {
                break;
            }
            porks.add(pork1);//加入到list
            parentid = pork1.getParent();

            if (pork1.getLevel() == 1) {//说明到达溯源终点
                Pig pig = pigService.selectByidpae(pork1.getParent());
                map.put("porks", porks);
                map.put("pig", pig);//最后还需要把猪这个实体放进去
                break;
            }
            if (count >= 5)
                break;
        }
        msg.setSuccess(map);
        return msg;
    }
}
